<script setup lang="ts">
import CpIcons from '@/components/cp-icons.vue'
import CpNavbar from '@/components/cp-navbar.vue'
import {
  createConsultOrder,
  getConsultOrderPayUrl,
  getConsultOrderPre,
  getPatientDetail
} from '@/services/consult'
import useConsultStore from '@/stores/modules/consult'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showLoadingToast, showToast } from 'vant'
import { onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

// 获取预支付信息
const consultStore = useConsultStore()
const payInfo = ref<ConsultOrderPreData>()
const getPayInfo = async () => {
  const res = await getConsultOrderPre({
    type: consultStore.consult.type,
    illnessType: consultStore.consult.illnessType
  })
  payInfo.value = res.data
  //   设置优惠卷
  consultStore.setCoupon(res.data.couponId)
}

// 获取患者信息
const patient = ref<Patient>()
const getPatient = async () => {
  if (!consultStore.consult.patientId) return
  const res = await getPatientDetail(consultStore.consult.patientId)
  patient.value = res.data
}

// 协议
const agree = ref(false)
const show = ref(false)
const loading = ref(false)
const paymentMethod = ref<0 | 1>() //选择的支付类型 0：微信 1：支付宝
const orderId = ref('') //生成的订单ID
// 支付逻辑
const next = async () => {
  // 判断协议是否勾选
  if (!agree.value) return showToast('请勾选我已同意支付协议')
  // 打开加载状态
  loading.value = true
  // 提交患者信息生成订单id
  const res = await createConsultOrder(consultStore.consult)
  // 存储订单id
  orderId.value = res.data.id
  //清空用户信息
  consultStore.clear()
  // 关闭加载状态
  loading.value = false
  // 显示支付方式框
  show.value = true
}

// 生成订单id后页面不能回退（利用页面的路由守卫）
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})

// 关闭支付弹窗
const router = useRouter()
const close = () => {
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)'
  })
    .then(() => {
      // 继续支付
      console.log('继续支付')
      show.value = true
    })
    .catch(() => {
      // 仍要关闭
      orderId.value = ''
      router.push('/user/consult')
    })
}

const pay = async () => {
  if (!paymentMethod.value) return showToast('请选择支付方式')
  showLoadingToast('跳转支付中')
  const res = await getConsultOrderPayUrl({
    orderId: orderId.value,
    paymentMethod: paymentMethod.value,
    payCallback: 'http://127.0.0.1:5173/room' //测试环境的地址
  })

  window.location.href = res.data.payUrl
}
onMounted(() => {
  // 组件初始化需要验证信息，反正页面刷新信息丢失
  if (
    !consultStore.consult.type ||
    !consultStore.consult.illnessType ||
    !consultStore.consult.depId ||
    !consultStore.consult.patientId
  ) {
    showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
    return
  }
  getPayInfo()
  getPatient()
})
</script>

<template>
  <div class="consult-pay-page">
    <CpNavbar title="支付" />
    <div class="pay-info" v-if="payInfo">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo?.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo?.actualPayment}`" class="pay-price" />
    </van-cell-group>

    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient?.name} | ${patient?.genderValue} | ${patient?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="consultStore.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>

    <van-submit-bar
      v-if="payInfo"
      :loading="loading"
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="next"
    />

    <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :close-on-popstate="false"
      @close="close"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付（微信支付接口未完成）" @click="paymentMethod = 0">
            <template #icon><CpIcons name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付(默认支付宝支付)" @click="paymentMethod = 1">
            <template #icon><CpIcons name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icons {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
